package com.mingxun.project.http.observer;

import com.mingxun.project.base.BaseView;
import com.mingxun.project.http.exception.ApiException;
import com.mingxun.project.http.exception.ExceptionEngine;
import com.utilmodule.LogUtil;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * class name：
 *
 * @author liuhongyuan.
 * @date 2017/12/22
 */

public abstract class BaseRxObserver<T> implements Observer<T> {
    private String mTag;//请求标识
    private BaseView mView;
    private boolean isShowProgress = true;

    public BaseRxObserver(BaseView view){
        mView = view;
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (mView != null && isShowProgress) {
            mView.showDialog("数据加载中...");
        }
    }

    @Override
    public void onNext(T value) {
        onSuccess(value);
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof ApiException) {
            onError((ApiException) e);
            LogUtil.v( "onError {" + ((ApiException)e).getMsg() + ": " + ((ApiException) e).getCode()+"}");
//            mView.showToast(((ApiException) e).getMsg());
        } else {
            ApiException error = new ApiException(e, ExceptionEngine.UN_KNOWN_ERROR);
            onError(error);
            LogUtil.v( "onError {" + error.getMsg() + ": " + error.getCode()+"}");
//            mView.showToast(error.getMsg());
        }
        if (mView != null && isShowProgress) {
            mView.hideDialog();
        }
    }

    @Override
    public void onComplete() {
        if (mView != null && isShowProgress) {
            mView.hideDialog();
//            mView.showToast("数据加载完成");
        }
    }

    /**
     * 错误/异常回调
     *
     * @author ZhongDaFeng
     */
    protected abstract void onError(ApiException error);

    /**
     * 成功回调
     *
     * @author ZhongDaFeng
     */
    protected abstract void onSuccess(T response);
}
